var models = require('../models');
const xlsx = require('node-xlsx');      // 读写xlsx的插件

Date.prototype.format = function(format) {
  var date = {
    "M+": this.getMonth() + 1,
    "d+": this.getDate(),
    "h+": this.getHours(),
    "m+": this.getMinutes(),
    "s+": this.getSeconds(),
    "q+": Math.floor((this.getMonth() + 3) / 3),
    "S+": this.getMilliseconds()
  };

  if (/(y+)/i.test(format)) {
    format = format.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  for (var k in date) {
    if (new RegExp("(" + k + ")").test(format)) {
      format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
    }
  }
  return format;
}

// 上传并更新数据库数据
exports.upload = async function(filePath) {
  let res = xlsx.parse(filePath);
  let header = res[0].data[0]
  let stuInfo = res[0].data.slice(1)
  let field = ['学号','姓名','性别','学院','录取专业','省份']
  let tempArr = field.map(item => {
    return header.indexOf(item)
  }).filter(temp => temp !== -1)

  await models.isdao.deleteMany({}) // 清空原来的表单
  stuInfo.forEach(ele => {
    models.isdao.create({
      '学号':ele[tempArr[0]],
      '姓名':ele[tempArr[1]],
      '性别':ele[tempArr[2]],
      '学院':ele[tempArr[3]],
      '专业':ele[tempArr[4]],
      '省份':ele[tempArr[5]],
      createTime: 0,
      isdao: 0
    })
  })
  return stuInfo
}

exports.findStudentByStuNo = async function(stuNo) {
  return await models.isdao.find({
    '学号': stuNo
  })
}

// 数据更新 --> 学生点击报道后更新
exports.updateStudent = async function (stuNo) {
  // 更新的内容 报道后isdao为1
  await models.isdao.updateOne({ 
      '学号': stuNo 
    }, { 
      'isdao': 1,
      'createTime': new Date().format('yyyy-MM-dd h:m:s')
    }
  )  
  return {
    isdaoResult: true,
    stuNo
  };
}

exports.updateNot = async function (stuNo) {
  await models.isdao.updateOne({  // 要更新的数据
    '学号': stuNo
  }, {  // 更新的内容 报道后isdao为0
    'isdao': 0
  })
  return {
    isdaoResult: false,
    stuNo
  };
}

exports.findStudent = async function (params) {
  let { keyWord, college, pageSize, pageNo } = params
  pageNo = pageNo ? pageNo : 1
  pageSize = pageSize ? pageSize : 10
  const condition = {
    $or : [ //多条件，数组
      {'学号' : {$regex : keyWord}},
      {'姓名' : {$regex : keyWord}}
    ],
    $and: [
      {'学院': {$regex: college}}
    ]
  }
  const total = await models.isdao.countDocuments(condition)

  const data = await models.isdao.find(condition,'',{
    sort: {'学号': 1},
    skip: (pageNo - 1) * pageSize,
    limit: Number(pageSize)
  });
  return {
    records: data,
    total,
    pageSize,
    pageNo
  }
}

// 统计报道总人数
exports.count = async function () {
  const reportNum = await models.isdao.countDocuments({
    'isdao': 1
  });
  const studentNum = await models.isdao.countDocuments({});
  return {
    reportNum,
    studentNum
  }
}

// 按照学院统计报道人数
exports.collegeCount = async function (college) {
  var isdao = await models.isdao.countDocuments({
    '学院': college,
    'isdao': 1
  })
  var collegeAll = await models.isdao.countDocuments({
    '学院': college,
  })
  return {
    'college' : college,
    'reportNum' : isdao,
    'collegeNum' : collegeAll
  }
}

exports.allCollege = async function () {
  var result = await models.isdao.aggregate([
    {
      $group: {
        '_id': "$学院",
        'reportNum' : {$sum : "$isdao"},
        'studentNum' : {$sum : 1}
      }
    }
  ]);
  return result;
}

exports.collegeSex = async function (college) {
  var collegeAllStu = await models.isdao.countDocuments({
    '学院': college,
  })
  var sexM = await models.isdao.countDocuments({
    '学院': college,
    '性别': '男'
  })
  var sexF = await models.isdao.countDocuments({
    '学院': college,
    '性别': '女'
  })
  return {
    'collegeNum': collegeAllStu,
    'sexNumM': sexM,
    'sexNumF': sexF,
    'sexProportion': (sexM / sexF).toFixed(3)
  }
}

// 男女生报道比例
exports.sexCountByIsdao = async function () {
  var sexM = await models.isdao.countDocuments({
    '性别': '男',
    'isdao': 1
  })
  var sexF = await models.isdao.countDocuments({
    '性别': '女',
    'isdao': 1
  })
  return { 
    sexM, 
    sexF,
    sexProportion : ((sexM / sexF).toFixed(2)) * 100 || 0
  };
}

// 全校男女生比例
exports.sexCount = async function () {
  var sexM = await models.isdao.countDocuments({
    '性别': '男',
  })
  var sexF = await models.isdao.countDocuments({
    '性别': '女',
  })
  return { 
    sexM, 
    sexF,
    sexProportion : ((sexM / sexF).toFixed(2)) || 0
  };
}

// 学院专业统计
exports.majorCount = async function(college) {
  let collegeData = await models.isdao.find({'学院': college})
  let result = []
  collegeData.forEach(ele => {
    if(!result.includes(ele['专业'])) result.push(ele['专业'])
  })
  return {
    major: result,
    count: result.length
  };
}

// 通过学院以及专业查询学生信息
exports.findStudentByMajor = async function (params) {
  const { college, major } = params
  const result = await models.isdao.find({
    $and: [
      {'学院': college},
      {'专业': major},
    ]
  })
  console.log(result)
  let reportNum = 0
  let unReportNum = 0
  result.forEach(ele => {
    if (ele.isdao) {
      reportNum++
    } else {
      unReportNum++
    }
  })
  return {
    records: result,
    reportNum,
    unReportNum,
    progress: reportNum / result.length,
    total: result.length
  }
}

exports.majorList = async function(college) {
  let collegeData = await models.isdao.find({'学院': college})
  let majorArr = []
  const result = []
  collegeData.forEach(ele => {
    if(!majorArr.includes(ele['专业'])) {
      majorArr.push(ele['专业'])
      result.push(getMajor(collegeData,ele['专业']))
    }
  })

  function getMajor(collegeData, major) {
    const majorList = collegeData.filter(ele => ele['专业'] === major)
    let reportNum = 0
    let unReportNum = 0
    majorList.forEach(ele => {
      if (ele.isdao) {
        reportNum++
      } else {
        unReportNum++
      }
    })
    return {
      major,
      reportNum,
      unReportNum,
      progress: reportNum / majorList.length,
      total: majorList.length
    }
  }

  return {
    college,
    majorList: result,
    majorCount: result.length
  };
}

/////////////////////////////////////////////////////////////////////////////

// 获取参数信息
exports.getConfig = async function (type) {
  let result = await models.reportConfig.find({type})
  console.log('result', result)
  return result
}

// 更改参数信息
exports.updateConfig = async function (params) {
  const hasType = await models.reportConfig.find({type: params.type})
  if (hasType.length) {
    await models.reportConfig.updateOne({
      type: params.type
    },{
      data: params.data,
      updateUser: params.updateUser,
      updateUserNo: params.updateUserNo,
      createTime: new Date().format('yyyy-MM-dd h:m:s')
    })
  } else {
    await models.reportConfig.create({
      type: params.type,
      data: params.data,
      updateUser: params.updateUser,
      updateUserNo: params.updateUserNo,
      createTime: new Date().format('yyyy-MM-dd h:m:s')
    })
  }
  return ''
}